﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.APP.FIM_Cheques;
using KPIS.GERP.ESS.APP.FIM_MoneyRequestDtls;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.DAL;
using KPIS.GERP.ESS.MODEL;
//using KPIS.GERP.ESS.IBLL;
//using KPIS.GERP.ESS.BLL;
//using KPIS.GERP.ESS.MODEL;
using _WebShared.Classes;
using Telerik.Web.UI;
using KPIS.DBM;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class Mail_Payment : System.Web.UI.UserControl
    {
        private Main main = new Main();
        private ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        private ESS.BLL.B_MessageReply reply = new ESS.BLL.B_MessageReply();
        private FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        //FIM_Petitions.FIM_Petitions pet = new FIM_Petitions.FIM_Petitions();
        //FIM_PetitionDtls.FIM_PetitionDtls petd = new FIM_PetitionDtls.FIM_PetitionDtls();
        private FIM_Payments.FIM_Payments pay = new FIM_Payments.FIM_Payments();
        private FIM_PaymentCheques.FIM_PaymentCheques paycheque = new FIM_PaymentCheques.FIM_PaymentCheques();
        private FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
        private FIM_MoneyRequestDtls.FIM_MoneyRequestDtls mrd = new FIM_MoneyRequestDtls.FIM_MoneyRequestDtls();
        private FIM_Cheques.FIM_Cheques c = new FIM_Cheques.FIM_Cheques();
        private KPIS.GERP.ESS.DAL.D_FimMoneyRequest mrDal = new D_FimMoneyRequest();

        private BGM_ProjectOperationReport.BGM_ProjectOperationReport rpt =
            new BGM_ProjectOperationReport.BGM_ProjectOperationReport();

        private B_HrmEmployees emplist = new B_HrmEmployees();
        D_HrmPositions pos = new D_HrmPositions();
        private B_SECURITY_Users user = new B_SECURITY_Users();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void LoadData(string strSendSeq, string strPaySeq, bool bEdit
            , string strApprovePathSeq, string strStatus, string strSender)
        {
            lblSendSeq.Text = strSendSeq;
            lblApprovePathSeq.Text = strApprovePathSeq;

            FIM_Payments.M_FIM_Payments payInfo = pay.GetInfo(strPaySeq);

            if (payInfo.money_req_seq.HasValue)
            {
                panelMoneyReq.Visible = true;
                FIM_MoneyRequests.M_FIM_MoneyRequests reqInfo = mr.GetInfo(payInfo.money_req_seq.ToString());

                lblMoneyReqSeq.Text = payInfo.money_req_seq.ToString();
                lblBgmProjOperCode.Text = reqInfo.bgm_proj_oper_code;
                lblBgmProjOperName.Text = reqInfo.bgm_proj_oper_name;
                lblBgmExpGrpName.Text = reqInfo.bgm_exp_grp_name;
                lblReqEmpName.Text = reqInfo.emp_name;
                lblPayeeName.Text = reqInfo.payee_name;
                lblPetitionNo.Text = reqInfo.petition_no;
                lblPetitionRefNo.Text = reqInfo.petition_ref_no;

                lblReqBathAmount.Text = (reqInfo.total_amount ?? 0).ToString("#,##0.00");
            }
            else
            {
                panelMoneyReq.Visible = false;
                PanelPetition.Visible = false;

                lblMoneyReqSeq.Text = "";
                lblPayeeName.Text = payInfo.payable_name;
                lblReqBathAmount.Text = (payInfo.amount ?? 0).ToString("#,##0.00");
            }

            lblEventName.Text = payInfo.event_name;
            lblVatPercent.Text = (payInfo.vat_rate ?? 0).ToString("#,##0.00");
            lblTaxPercent.Text = (payInfo.tax_rate ?? 0).ToString("#,##0.00");
            lblVatAmount.Text = (payInfo.vat ?? 0).ToString("#,##0.00");
            lblTaxAmount.Text = (payInfo.tax ?? 0).ToString("#,##0.00");
            lblPenalty.Text = (payInfo.penalty_amount ?? 0).ToString("#,##0.00");
            lblRedemption.Text = (payInfo.redemption_amount ?? 0).ToString("#,##0.00");
            lblPayAmount.Text = (payInfo.amount ?? 0).ToString("#,##0.00");

            lblPaySeq.Text = strPaySeq;
            lblPayRefNo.Text = payInfo.ref_no;
            lblPayDate.Text = payInfo.pay_date.Value.ToShortDateString();
            lblPayName.Text = payInfo.pay_name;
            lblMethodSeq.Text = payInfo.method_seq.ToString();
            lblMethodName.Text = payInfo.method_name;

            PanelCheque.Visible = lblMethodSeq.Text == "2";

            if (PanelCheque.Visible)
            {
                LoadDataCheque();
            }

            bool bEnable = strStatus == "2";
            cmdApprove.Enabled = !bEnable && bEdit;
            cmdForword.Enabled = !bEnable && bEdit;
            cmdSendBack.Enabled = !bEnable && bEdit;
            PanelOption.Visible = true;
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            PanelSend.Visible = false;
            txtRemark.Text = "";
            LoadApprover();
            //SetApproverRight();
        }

        protected void LoadApprover()
        {
            int nStepNo = 1;
            string strNextStepNo = send.GetNextStepNo(lblApprovePathSeq.Text, lblPayAmount.Text);

            if (Int32.TryParse(strNextStepNo, out nStepNo))
            {
                if (nStepNo > 0)
                {
                    cmdApprove.Visible = false;
                    cmdForword.Visible = true;


                    // Edit by Aek 2014-07-29
                    // Calculate base on to_emp_seq field in table message_send, not login session 
                    DataTable dtb = send.GetCurrentApprover(null, lblSendSeq.Text, "FIM_PAYMENTS", nStepNo);


                    if (dtb != null)
                    {
                        if (dtb.Rows.Count > 0)
                        {
                            lblApproverEmpSeq.Text = dtb.Rows[0]["emp_seq"].ToString();
                            lblApproverPosSeq.Text = dtb.Rows[0]["pos_seq"].ToString();
                            LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString(), dtb.Rows[0]["pos_seq"].ToString());
                        }
                    }
                }
                else
                {
                    cmdApprove.Visible = true;
                    cmdForword.Visible = false;
                }
            }
        }

        protected void LoadDataCheque()
        {
            grdCheque.DataSource = paycheque.GetFull(lblPaySeq.Text, null);
            grdCheque.DataBind();
        }

        //protected void SetApproverRight()
        //{
        //    cmdApprove.Visible = user.CheckIsApprover(Session["EmpSeq"].ToString());
        //}
        public void cmdApprove_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = true;
            PanelSendTo.Visible = false;
            lblMode.Text = "A";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdForword_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = true;
            lblMode.Text = "F";

            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
        }

        protected void cmdSendBack_Click(object sender, EventArgs e)
        {
            lblMode.Text = "B";

            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = true;
            // button
            PanelOption.Visible = false;
            PanelSend.Visible = true;
            lblError.Text = "";
        }

        protected void LoadEmpInfo(string strEmpSeq, string strPosSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproverEmpSeq.Text = strEmpSeq;
                lblApproverPosSeq.Text = strPosSeq;// dtb.Rows[0]["t_pos_seq"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
                lblApproverClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblApproverExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblApproverJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();

                if (!string.IsNullOrEmpty(strPosSeq) && dtb.Rows[0]["t_pos_seq"].ToString() != strPosSeq)
                {
                    DataTable dtb2 = pos.GetPosition(strPosSeq);

                    lblApproverPosName.Text = "รักษาการณ์ตำแหน่ง " + dtb2.Rows[0]["pos_name"].ToString();
                }
                else
                {
                    lblApproverPosSeq.Text = dtb.Rows[0]["t_pos_seq"].ToString();
                    lblApproverPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                }
            }
        }

        private bool directApprove = false;

        public string Approve(string remark)
        {
            cmdApprove_Click(new Object(), new EventArgs());
            txtRemark.Text = remark;
            return cmdSendClick();
        }

        public void cmdSend_Click(object sender, EventArgs e)
        {
            cmdSendClick();
        }

        public string cmdSendClick()
        {
            string strSQL = "";
            string errrorMessage = "";
            errrorMessage += "Start, ";
            int nEmpSeqLogin = SsMng.EmpSeqI;
            //BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            FIM_Payments.M_FIM_Payments payInfo = new FIM_Payments.M_FIM_Payments();
            ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
            ESS.MODEL.M_MessageReply replyInfo = new ESS.MODEL.M_MessageReply();
            errrorMessage += "Created services, ";
            string strPaySeq = lblPaySeq.Text;

            // By Aek 2014-07-29
            // remark: in forwarding FromEmpSeq should be the previous emp_seq in message_send
            // string strFromEmpSeq = Session["EmpSeq"].ToString();
            var messageSendPrev = send.GetFull(null, null, null, null, null, null, null, lblSendSeq.Text)[0];
            string strFromEmpSeq = messageSendPrev.to_emp_seq.ToString();
            string strFromPosSeq = messageSendPrev.to_pos_seq.ToString();

            int nFromEmpSeq = Convert.ToInt32(strFromEmpSeq);
            int nFromPosSeq = Convert.ToInt32(strFromPosSeq);

            Nullable<int> nToEmpSeq = null;
            Nullable<int> nToPosSeq = null;
            Nullable<int> nWodEmpSeq = nEmpSeqLogin == nFromEmpSeq ? (int?)null : nEmpSeqLogin;

            errrorMessage += "Got To-From pos seq, ";

            bool bLeaf = true;
            string strSendSeq = lblSendSeq.Text;
            string strToEmpSeq = lblApproverEmpSeq.Text;
            string strToPosSeq = lblApproverPosSeq.Text;

            if (strToEmpSeq.Length == 0 && ddlApprover.Visible)
            {
                lblError.Text = "คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง";
                return lblError.Text;
            }
            else
            {
                lblError.Text = "";
            }

            errrorMessage += "set label, ";


            while (bLeaf)
            {
                ESS.MODEL.M_MessageSend sendInfo = send.GetInfo(strSendSeq);
                string strFromSendSeq = sendInfo.from_send_seq.ToString();

                if (string.IsNullOrEmpty(strFromSendSeq))
                {
                    bLeaf = false;
                    nToEmpSeq = sendInfo.from_emp_seq;
                    nToPosSeq = send.GetPosSeqFromEmpSeq(Convert.ToString(nToEmpSeq));
                }

                strSendSeq = strFromSendSeq;
            }

            errrorMessage += "pass loop bLeaf, ";

            switch (lblMode.Text)
            {
                case "A":
                    #region A
                    DateTime date = DateTime.Now;
                    dbManager.Open();
                    dbManager.BeginTransaction();

                    try
                    {
                        //dbManager.CreateParameters(1);
                        //dbManager.AddParameters(0, "@created_when", date);

                        //strSQL = "select count(*) as row_count"
                        //    + " from bgm_project_operation_report"
                        //    + " where DATEDIFF(SECOND, created_when, @created_when) < 30";
                        //var exists = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                        //if (exists.Rows.Count > 0 && (main.ConvertNullInt(exists.Rows[0][0]) ?? 0) > 0)
                        //{
                        //    dbManager.RollBackTransaction();
                        //    main.MessageAlert(Page, "มีการทำรายการซ้ำ");
                        //    return "";
                        //}

                        errrorMessage += "Case Mode A, ";
                        payInfo.pay_seq = Convert.ToInt32(strPaySeq);
                        payInfo.record_status = "A";
                        payInfo.updated_by = nEmpSeqLogin;
                        payInfo.updated_when = DateTime.Now;

                        dbManager.CreateParameters(4);

                        dbManager.AddParameters(0, "@pay_seq", payInfo.pay_seq);
                        dbManager.AddParameters(1, "@record_status", payInfo.record_status);
                        dbManager.AddParameters(2, "@updated_by", payInfo.updated_by);
                        dbManager.AddParameters(3, "@updated_when", payInfo.updated_when);

                        strSQL = "select record_status from fim_payments where pay_seq = @pay_seq";
                        DataTable dtb = dbManager.ExecuteDataTable(CommandType.Text, strSQL);

                        if (dtb.Rows.Count > 0)
                        {
                            if (dtb.Rows[0][0].ToString() == "A")
                            {
                                main.MessageAlert(Page, "รายการนี้อนุมัติไปแล้ว กรุณาอย่ากดซ้ำ");
                                return "";
                            }
                        }

                        strSQL = "UPDATE fim_payments"
                            + " SET record_status = @record_status"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                            + " WHERE pay_seq = @pay_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        errrorMessage += "Pass Change Status, ";

                        dbManager.AddParameters(0, "@delete_status", SystemInfo._DeleteRecordStatus);
                        dbManager.AddParameters(1, "@seq", lblPaySeq.Text);
                        dbManager.AddParameters(2, "@rpt_type", "6");

                        int nPrevRptType = 0;
                        strSQL = "select rpt.*"
                            + " from bgm_project_operation_report rpt"
                            + " left join fim_money_request_dtls mrd on rpt.money_req_dtls_seq = mrd.money_req_dtls_seq"
                            + " left join fim_payments pay on mrd.money_req_seq = pay.money_req_seq"

                            + " where rpt.record_status not like @delete_status"
                            + " and pay.pay_seq = @seq"
                            + " and rpt.rpt_type = @rpt_type";

                        var drc = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows;
                        if (drc.Count > 0)
                        {
                            for (int i = 0; i < drc.Count; i++)
                            {
                                BGM_ProjectOperationReport.M_BGM_ProjectOperationReport item = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                                item.bgm_proj_oper_rpt_seq = Convert.ToInt32(drc[i]["bgm_proj_oper_rpt_seq"]);
                                item.bgm_proj_oper_exp_seq = main.ConvertNullInt(drc[i]["bgm_proj_oper_exp_seq"]);
                                //item.bgm_trans_from_seq = main.ConvertNullInt(drc[i]["bgm_trans_from_seq"]);
                                //item.bgm_trans_to_seq = main.ConvertNullInt(drc[i]["bgm_trans_to_seq"]);
                                item.icm_ppr_item_seq = main.ConvertNullInt(drc[i]["icm_ppr_item_seq"]);
                                item.icm_pr_item_seq = main.ConvertNullInt(drc[i]["icm_pr_item_seq"]);
                                item.icm_dn_item_seq = main.ConvertNullInt(drc[i]["icm_dn_item_seq"]);
                                item.money_req_dtls_seq = main.ConvertNullInt(drc[i]["money_req_dtls_seq"]);
                                item.return_dtls_seq = main.ConvertNullInt(drc[i]["return_dtls_seq"]);
                                item.petition_dtls_seq = main.ConvertNullInt(drc[i]["petition_dtls_seq"]);
                                item.pay_seq = main.ConvertNullInt(drc[i]["pay_seq"]);
                                item.used_amount = main.ConvertNullDouble(drc[i]["used_amount"]);
                                item.cal_amount = main.ConvertNullDouble(drc[i]["cal_amount"]);
                                item.rpt_type = main.ConvertNullInt(drc[i]["rpt_type"]);
                                //item.receive_seq = cn.ConvertNullInt(drc[0]["receive_seq"]);

                                dbManager.CreateParameters(13);

                                dbManager.AddParameters(0, "@bgm_proj_oper_rpt_seq", item.bgm_proj_oper_rpt_seq);
                                dbManager.AddParameters(1, "@descr", item.descr);
                                dbManager.AddParameters(2, "@bgm_proj_oper_exp_seq", item.bgm_proj_oper_exp_seq);
                                dbManager.AddParameters(3, "@bgm_trans_from_seq", "");
                                dbManager.AddParameters(4, "@bgm_trans_to_seq", "");
                                dbManager.AddParameters(5, "@money_req_dtls_seq", item.money_req_dtls_seq);
                                dbManager.AddParameters(6, "@return_dtls_seq", item.return_dtls_seq);
                                dbManager.AddParameters(7, "@petition_dtls_seq", item.petition_dtls_seq);
                                dbManager.AddParameters(8, "@pay_seq", item.pay_seq);

                                dbManager.AddParameters(9, "@used_amount", item.used_amount);
                                dbManager.AddParameters(10, "@cal_amount", 0);

                                dbManager.AddParameters(11, "@updated_by", item.updated_by);
                                dbManager.AddParameters(12, "@updated_when", item.updated_when);

                                strSQL = "UPDATE bgm_project_operation_report"
                                    + " set descr = @descr"
                                    + ", bgm_proj_oper_exp_seq = @bgm_proj_oper_exp_seq"
                                    //+ ", bgm_trans_from_seq = @bgm_trans_from_seq"
                                    //+ ", bgm_trans_to_seq = @bgm_trans_to_seq"
                                    + ", money_req_dtls_seq = @money_req_dtls_seq"
                                    + ", return_dtls_seq = @return_dtls_seq"
                                    + ", petition_dtls_seq = @petition_dtls_seq"
                                    + ", pay_seq = @pay_seq"
                                    //+ ", receive_seq = @receive_seq"
                                    + ", used_amount = @used_amount"
                                    + ", cal_amount = @cal_amount"

                                    + ", updated_by = @updated_by"
                                    + ", updated_when = @updated_when"
                                    + " WHERE bgm_proj_oper_rpt_seq = @bgm_proj_oper_rpt_seq";

                                dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                            }
                        }
                        errrorMessage += "Pass Loop Report Old list, ";

                        if (lblMoneyReqSeq.Text.Length > 0)
                        {
                            dbManager.CreateParameters(2);

                            dbManager.AddParameters(0, "@delete_status", SystemInfo._DeleteRecordStatus);
                            dbManager.AddParameters(1, "@money_req_seq", lblMoneyReqSeq.Text);

                            strSQL = "SELECT mrd.money_req_dtls_seq, mrd.money_req_seq, mrd.money_req_dtls_name"
                                + ", mrd.bgm_proj_oper_exp_seq, mrd.percent_vat, mrd.percent_tax"
                                + ", mrd.amount, mrd.amount_vat, mrd.amount_tax, mrd.amount_fund, mrd.bath_amount_tax"
                                + ", coalesce(mrd.amount, 0) - coalesce(mrd.amount_vat, 0) as exclude_vat"

                                + ", recexp.bgm_exp_seq, exp.bgm_exp_name, exp.bgm_exp_grp_seq"
                                + ", exp1.bgm_exp_seq as bgm_exp_seq1, exp1.bgm_exp_name as bgm_exp_name1"
                                + ", exp2.bgm_exp_seq as bgm_exp_seq2, exp2.bgm_exp_name as bgm_exp_name2"

                                + ", mrd.record_status, mrd.remarks"
                                + ", mrd.created_by, mrd.created_when, mrd.updated_by, mrd.updated_when"
                                + " FROM fim_money_request_dtls mrd"
                                + " LEFT JOIN bgm_project_operation_expense pjexp ON mrd.bgm_proj_oper_exp_seq = pjexp.bgm_proj_oper_exp_seq"
                                + " LEFT JOIN bgm_project_expense recexp ON pjexp.bgm_proj_exp_seq = recexp.bgm_proj_exp_seq"
                                + " LEFT JOIN bgm_mas_expense exp ON recexp.bgm_exp_seq = exp.bgm_exp_seq"
                                + " LEFT JOIN bgm_mas_expense exp1 ON exp.upper_bgm_exp_seq = exp1.bgm_exp_seq"
                                + " LEFT JOIN bgm_mas_expense exp2 ON exp1.upper_bgm_exp_seq = exp2.bgm_exp_seq"
                                + " WHERE mrd.record_status not like @delete_status"
                                + " and mrd.money_req_seq = @money_req_seq"
                                + " ORDER BY mrd.money_req_dtls_seq";

                            drc = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows;
                            if (drc.Count > 0)
                            {
                                for (int i = 0; i < drc.Count; i++)
                                {
                                    FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls item = new FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls();
                                    item.money_req_dtls_seq = Convert.ToInt32(drc[i]["money_req_dtls_seq"]);
                                    item.money_req_seq = main.ConvertNullInt(drc[i]["money_req_seq"]);
                                    item.money_req_dtls_name = drc[i]["money_req_dtls_name"].ToString();
                                    item.bgm_proj_oper_exp_seq = main.ConvertNullInt(drc[i]["bgm_proj_oper_exp_seq"]);
                                    item.percent_vat = main.ConvertNullDouble(drc[i]["percent_vat"]);
                                    item.percent_tax = main.ConvertNullDouble(drc[i]["percent_tax"]);
                                    item.amount = main.ConvertNullDouble(drc[i]["amount"]);
                                    item.amount_vat = main.ConvertNullDouble(drc[i]["amount_vat"]);
                                    item.amount_tax = main.ConvertNullDouble(drc[i]["amount_tax"]);
                                    item.amount_fund = main.ConvertNullDouble(drc[i]["amount_fund"]);
                                    item.remarks = drc[i]["remarks"].ToString();
                                    item.exclude_vat = main.ConvertNullDouble(drc[i]["exclude_vat"]);
                                    item.bath_amount_tax = main.ConvertNullDouble(drc[i]["bath_amount_tax"]);
                                    item.bgm_exp_name = drc[i]["bgm_exp_name"].ToString();

                                    item.record_status = drc[i]["record_status"].ToString();
                                    item.created_by = main.ConvertNullInt(drc[i]["created_by"]);
                                    item.created_when = main.ConvertNullDateTime(drc[i]["created_when"]);
                                    item.updated_by = main.ConvertNullInt(drc[i]["updated_by"]);
                                    item.updated_when = main.ConvertNullDateTime(drc[i]["updated_when"]);
                                    BGM_ProjectOperationReport.M_BGM_ProjectOperationReport reportInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                                    reportInfo.bgm_proj_oper_exp_seq = item.bgm_proj_oper_exp_seq;
                                    reportInfo.descr = lblPayName.Text;
                                    reportInfo.pay_seq = main.ConvertNullInt(lblPaySeq.Text);
                                    reportInfo.used_amount = item.amount;
                                    reportInfo.cal_amount = -item.amount;
                                    reportInfo.rpt_type = 7;//จ่าย
                                    reportInfo.created_by = nEmpSeqLogin;
                                    reportInfo.created_when = date;

                                    dbManager.CreateParameters(15);

                                    dbManager.AddParameters(0, "@bgm_proj_oper_rpt_seq", reportInfo.bgm_proj_oper_rpt_seq);
                                    dbManager.AddParameters(1, "@descr", reportInfo.descr);
                                    dbManager.AddParameters(2, "@bgm_proj_oper_exp_seq", reportInfo.bgm_proj_oper_exp_seq);
                                    dbManager.AddParameters(3, "@bgm_trans_from_seq", "");
                                    dbManager.AddParameters(4, "@bgm_trans_to_seq", "");
                                    dbManager.AddParameters(5, "@money_req_dtls_seq", reportInfo.money_req_dtls_seq);
                                    dbManager.AddParameters(6, "@return_dtls_seq", reportInfo.return_dtls_seq);
                                    dbManager.AddParameters(7, "@petition_dtls_seq", reportInfo.petition_dtls_seq);
                                    dbManager.AddParameters(8, "@pay_seq", reportInfo.pay_seq);

                                    dbManager.AddParameters(9, "@used_amount", reportInfo.used_amount);
                                    dbManager.AddParameters(10, "@cal_amount", reportInfo.cal_amount);
                                    dbManager.AddParameters(11, "@rpt_type", reportInfo.rpt_type);

                                    dbManager.AddParameters(12, "@record_status", SystemInfo._ActiveRecordStatus);
                                    dbManager.AddParameters(13, "@created_by", reportInfo.created_by);
                                    dbManager.AddParameters(14, "@created_when", reportInfo.created_when);

                                    //strSQL = "select count(*) as row_count"
                                    //    + " from bgm_project_operation_report"
                                    //    + " where created_when = @bgm_proj_oper_exp_seq"
                                    //    + " and used_amount = @used_amount"
                                    //    + " and cal_amount = @cal_amount"
                                    //    + " and cal_amount <> 0"
                                    //    + " and rpt_type = @rpt_type"
                                    //    + " and DATEDIFF(SECOND, created_when, GETDATE()) < 30";
                                    //var exists = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                                    //if (exists.Rows.Count > 0 && (main.ConvertNullInt(exists.Rows[0][0]) ?? 0) > 0)
                                    //{
                                    //    dbManager.RollBackTransaction();
                                    //    main.MessageAlert(Page, "มีการทำรายการซ้ำ");
                                    //    return "";
                                    //}

                                    strSQL = "INSERT INTO bgm_project_operation_report"
                                        + "(descr, bgm_proj_oper_exp_seq"//, bgm_trans_from_seq, bgm_trans_to_seq"
                                            + ", money_req_dtls_seq, return_dtls_seq, petition_dtls_seq, pay_seq"
                                            + ", used_amount, cal_amount, rpt_type"
                                            + ", record_status, created_by, created_when)"
                                        + " VALUES (@descr, @bgm_proj_oper_exp_seq"//, @bgm_trans_from_seq, @bgm_trans_to_seq"
                                            + ", @money_req_dtls_seq, @return_dtls_seq, @petition_dtls_seq, @pay_seq"
                                            + ", @used_amount, @cal_amount, @rpt_type"
                                            + ", @record_status, @created_by, @created_when)";

                                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                                }
                            }
                        }

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_type = "1";
                        replyInfo.reply_text = "อนุมัติ : " + lblPayName.Text;
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        replyInfo.remarks = txtRemark.Text;

                        dbManager.CreateParameters(16);

                        dbManager.AddParameters(0, "@reply_seq", replyInfo.reply_seq);
                        dbManager.AddParameters(1, "@reply_date", replyInfo.reply_date == null ? DBNull.Value : (object)replyInfo.reply_date);
                        dbManager.AddParameters(2, "@ref_no", replyInfo.ref_no == null ? DBNull.Value : (object)replyInfo.ref_no);
                        dbManager.AddParameters(3, "@reply_text", replyInfo.reply_text == null ? DBNull.Value : (object)replyInfo.reply_text);
                        dbManager.AddParameters(4, "@reply_type", replyInfo.reply_type == null ? DBNull.Value : (object)replyInfo.reply_type);
                        dbManager.AddParameters(5, "@from_emp_seq", replyInfo.from_emp_seq == null ? DBNull.Value : (object)replyInfo.from_emp_seq);
                        dbManager.AddParameters(6, "@to_emp_seq", replyInfo.to_emp_seq == null ? DBNull.Value : (object)replyInfo.to_emp_seq);
                        dbManager.AddParameters(7, "@from_send_seq", replyInfo.from_send_seq == null ? DBNull.Value : (object)replyInfo.from_send_seq);
                        dbManager.AddParameters(8, "@remarks", replyInfo.remarks == null ? DBNull.Value : (object)replyInfo.remarks);
                        dbManager.AddParameters(9, "@message_status", replyInfo.message_status == null ? DBNull.Value : (object)replyInfo.message_status);

                        dbManager.AddParameters(10, "@record_status", SystemInfo._ActiveRecordStatus);
                        dbManager.AddParameters(11, "@created_by", replyInfo.created_by);
                        dbManager.AddParameters(12, "@created_when", replyInfo.created_when);

                        dbManager.AddParameters(13, "@from_pos_seq", replyInfo.from_pos_seq);
                        dbManager.AddParameters(14, "@to_pos_seq", replyInfo.to_pos_seq);
                        dbManager.AddParameters(15, "@wod_emp_seq", replyInfo.wod_emp_seq);

                        strSQL = "INSERT INTO message_reply"
                            + "(reply_date, ref_no, reply_text, reply_type"
                            + ", from_emp_seq, to_emp_seq, from_send_seq, remarks, message_status"
                            + ", from_pos_seq, to_pos_seq, wod_emp_seq"
                            + ", record_status, created_by, created_when)"
                            + " VALUES(@reply_date"
                                + ", @ref_no"
                                + ", @reply_text"
                                + ", @reply_type"
                                + ", @from_emp_seq"
                                + ", @to_emp_seq"
                                + ", @from_send_seq"
                                + ", @remarks"
                                + ", @message_status"
                                + ", @from_pos_seq"
                                + ", @to_pos_seq"
                                + ", @wod_emp_seq"

                                + ", @record_status"
                                + ", @created_by"
                                + ", @created_when);"
                            + " SELECT scope_identity();";
                        var strSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;

                        dbManager.CreateParameters(5);

                        dbManager.AddParameters(0, "@send_seq", info.send_seq);
                        dbManager.AddParameters(1, "@message_status", info.message_status);
                        dbManager.AddParameters(2, "@updated_by", info.updated_by);
                        dbManager.AddParameters(3, "@updated_when", info.updated_when);
                        dbManager.AddParameters(4, "@wod_emp_seq", info.wod_emp_seq);

                        strSQL = "UPDATE message_send"
                            + " SET message_status = @message_status"
                            + ", updated_by = @updated_by"
                            + ", updated_when = @updated_when"
                                 + ", wod_emp_seq = @wod_emp_seq"
                            + " WHERE send_seq = @send_seq";

                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        dbManager.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        dbManager.RollBackTransaction();
                        string errorStr = ex.Message + " " + ex.InnerException;
                        if (!directApprove) new Main().MessageAlert(Page, errorStr);
                        return errorStr;
                    }
                    finally
                    {
                        dbManager.Dispose();
                    }
                    #endregion
                    break;
                case "F":
                    payInfo.pay_seq = Convert.ToInt32(strPaySeq);
                    payInfo.record_status = "P";
                    payInfo.updated_by = nEmpSeqLogin;
                    payInfo.updated_when = DateTime.Now;
                    pay.ChangeStatus(payInfo);

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(strPaySeq);
                    info.ref_type = "fim_payments";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    info.send_text = "ขออนุมัติ " + lblPayName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;
                    info.to_emp_seq = main.ConvertNullInt(strToEmpSeq);
                    info.to_pos_seq = main.ConvertNullInt(strToPosSeq);
                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;

                    if (main.CheckDuplicateMessage(lblSendSeq.Text))
                    {
                        main.MessageAlert(Page, "รายการนี้ส่งไปแล้ว กรุณาอย่ากดซ้ำ");
                        return "";
                    }

                    send.Insert(info);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
                case "B":
                    payInfo.pay_seq = Convert.ToInt32(strPaySeq);
                    payInfo.record_status = "R";
                    payInfo.updated_by = nEmpSeqLogin;
                    payInfo.updated_when = DateTime.Now;
                    pay.ChangeStatus(payInfo);

                    info.send_date = DateTime.Today;
                    info.ref_seq = main.ConvertNullInt(strPaySeq);
                    info.ref_type = "return";
                    info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    info.send_text = "ส่งกลับเพื่อแก้ไข : " + lblPayName.Text;
                    info.from_emp_seq = nFromEmpSeq;
                    info.from_pos_seq = nFromPosSeq;
                    info.to_emp_seq = nToEmpSeq;
                    info.to_pos_seq = nToPosSeq;
                    info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                    info.remarks = txtRemark.Text;
                    info.message_status = "0";
                    info.approve_path_seq = null; //main.ConvertNullInt(lblNewApprovePathSeq.Text);
                    info.created_by = nEmpSeqLogin;
                    info.created_when = DateTime.Now;
                    send.Insert(info);

                    replyInfo.reply_date = DateTime.Today;
                    replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                    replyInfo.reply_type = "0";
                    replyInfo.reply_text = "ส่งกลับมาเพื่อแก้ไข";
                    replyInfo.from_emp_seq = nFromEmpSeq;
                    replyInfo.from_pos_seq = nFromPosSeq;
                    replyInfo.to_emp_seq = nToEmpSeq;
                    replyInfo.to_pos_seq = nToPosSeq;
                    replyInfo.wod_emp_seq = nWodEmpSeq;
                    replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                    replyInfo.remarks = txtRemark.Text;
                    replyInfo.message_status = "0";
                    replyInfo.created_by = nEmpSeqLogin;
                    replyInfo.created_when = DateTime.Now;
                    reply.Insert(replyInfo);

                    info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                    info.message_status = "2";
                    info.wod_emp_seq = nWodEmpSeq;
                    info.updated_by = nEmpSeqLogin;
                    info.updated_when = DateTime.Now;
                    send.UpdateMessageStatus(info);
                    break;
            }

                ((TaskListsPopUp)Page).cmdViewRequest_Click(null, null);
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            // button
            PanelOption.Visible = true;
            PanelSend.Visible = false;
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text =
                Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadEmpInfo(ddlApprover.SelectedValue, null);
        }
    }
}